<template>
  <div class="contract-draft">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable />
        </el-form-item>
        <el-form-item label="合同名称">
          <el-input v-model="searchForm.contractName" placeholder="请输入合同名称" clearable />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="searchForm.contractType" placeholder="请选择合同类型" clearable>
            <el-option
              v-for="item in contractTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增合同</el-button>
      <el-button type="success" @click="handleAddFromTemplate">从模板创建</el-button>
      <el-button type="success" @click="handleBatchSubmit" :disabled="!selectedRows.length">
        批量提交审批
      </el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="contractNo" label="合同编号" width="150" />
        <el-table-column prop="contractName" label="合同名称" min-width="200" />
        <el-table-column prop="contractTypeName" label="合同类型" width="120" />
        <el-table-column prop="totalAmount" label="合同金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="signedDate" label="签订日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.signedDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="statusName" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" @click="handleSubmit(scope.row)" v-if="scope.row.status === 0">
              提交审批
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" v-if="scope.row.status === 0">
              删除
            </el-button>
            <el-button type="info" size="small" @click="handleViewDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择合同类型" style="width: 100%">
                <el-option
                  v-for="item in contractTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="签订日期" prop="signedDate">
              <el-date-picker
                v-model="form.signedDate"
                type="date"
                placeholder="选择签订日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="totalAmount">
              <el-input-number
                v-model="form.totalAmount"
                :precision="2"
                :min="0"
                style="width: 100%"
                placeholder="请输入合同金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板选择对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="选择合同模板"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="template-selection">
        <el-form :inline="true" class="template-filter">
          <el-form-item label="模板类型">
            <el-select v-model="templateFilter.type" placeholder="请选择模板类型" clearable @change="loadTemplateList">
              <el-option label="销售合同模板" value="SALE" />
              <el-option label="采购合同模板" value="PURCHASE" />
            </el-select>
          </el-form-item>
        </el-form>
        
        <el-table
          :data="templateList"
          v-loading="templateLoading"
          @row-click="handleTemplateSelect"
          border
          stripe
        >
          <el-table-column prop="templateName" label="模板名称" min-width="200" />
          <el-table-column prop="templateTypeName" label="模板类型" width="120" />
          <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="150">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="合同详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="contractDetail" class="contract-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同编号">{{ contractDetail.contractNo }}</el-descriptions-item>
          <el-descriptions-item label="合同名称">{{ contractDetail.contractName }}</el-descriptions-item>
          <el-descriptions-item label="合同类型">{{ contractDetail.contractTypeName }}</el-descriptions-item>
          <el-descriptions-item label="合同金额">{{ formatMoney(contractDetail.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="签订日期">{{ formatDate(contractDetail.signedDate) }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ formatDate(contractDetail.startDate) }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ formatDate(contractDetail.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="getStatusTagType(contractDetail.status)">{{ contractDetail.statusName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(contractDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(contractDetail.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ contractDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 合同明细 -->
        <div v-if="contractDetail.contractItems && contractDetail.contractItems.length > 0" class="contract-items">
          <h3>合同明细</h3>
          <el-table :data="contractDetail.contractItems" border stripe>
            <el-table-column prop="productName" label="产品名称" min-width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unitName" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="scope">
                {{ formatMoney(scope.row.unitPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="小计" width="120">
              <template #default="scope">
                {{ formatMoney(scope.row.totalAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { contractApi } from '@/api/contract/contract'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "contract_draft",
  data() {
    return {
      // 搜索表单
      searchForm: {
        contractNo: '',
        contractName: '',
        contractType: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 选中的行
      selectedRows: [],
      // 对话框显示状态
      dialogVisible: false,
      // 对话框标题
      dialogTitle: '',
      // 表单数据
      form: {
        contractName: '',
        contractType: '',
        signedDate: '',
        startDate: '',
        endDate: '',
        totalAmount: 0,
        remark: ''
      },
      // 表单验证规则
      rules: {
        contractName: [
          { required: true, message: '请输入合同名称', trigger: 'blur' }
        ],
        contractType: [
          { required: true, message: '请选择合同类型', trigger: 'change' }
        ],
        signedDate: [
          { required: true, message: '请选择签订日期', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        endDate: [
          { required: true, message: '请选择结束日期', trigger: 'change' }
        ],
        totalAmount: [
          { required: true, message: '请输入合同金额', trigger: 'blur' }
        ]
      },
      // 合同类型列表
      contractTypeList: [],
      // 表单引用
      formRef: null,
      // 编辑模式
      isEdit: false,
      // 编辑的合同ID
      editId: null,
      // 模板选择相关
      templateDialogVisible: false,
      templateFilter: {
        type: ''
      },
      templateList: [],
      templateLoading: false,
      // 合同详情对话框
      detailDialogVisible: false,
      contractDetail: null
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    // 初始化数据
    async initData() {
      await this.getContractTypeList()
      this.loadTableData()
    },

    // 获取合同类型列表
    async getContractTypeList() {
      try {
        const res = await contractApi.getContractTypeList()
        if (res.code === 200) {
          this.contractTypeList = res.data
        }
      } catch (error) {
        console.error('获取合同类型列表失败:', error)
      }
    },

    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size,
          status: 0 // 只查询草稿状态的合同
        }
        const res = await contractApi.getContractPage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        contractNo: '',
        contractName: '',
        contractType: ''
      }
      this.handleSearch()
    },

    // 选择行变化
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },

    // 新增合同
    handleAdd() {
      this.isEdit = false
      this.editId = null
      this.dialogTitle = '新增合同'
      this.form = {
        contractName: '',
        contractType: '',
        signedDate: '',
        startDate: '',
        endDate: '',
        totalAmount: 0,
        remark: ''
      }
      this.dialogVisible = true
    },

    // 新增合同从模板
    handleAddFromTemplate() {
      this.templateDialogVisible = true
      this.templateFilter.type = '' // 清空类型，加载所有模板
      this.loadTemplateList()
    },

    // 加载模板列表
    async loadTemplateList() {
      this.templateLoading = true
      try {
        const res = await contractApi.getContractTemplateList(this.templateFilter.type)
        if (res.code === 200) {
          this.templateList = res.data
        } else {
          ElMessage.error(res.message || '加载模板失败')
        }
      } catch (error) {
        console.error('加载模板列表失败:', error)
        ElMessage.error('加载模板失败')
      } finally {
        this.templateLoading = false
      }
    },

    // 选择模板
    handleTemplateSelect(row) {
      this.form = {
        contractName: row.templateName,
        contractType: row.templateType,
        signedDate: '', // 模板没有签订日期
        startDate: '',
        endDate: '',
        totalAmount: 0,
        remark: row.description || ''
      }
      this.templateDialogVisible = false // 关闭模板选择对话框
      this.dialogVisible = true
      this.dialogTitle = '从模板创建合同'
      this.isEdit = false // 表示是从模板创建，不是编辑
      this.editId = null
    },

    // 编辑合同
    handleEdit(row) {
      this.isEdit = true
      this.editId = row.id
      this.dialogTitle = '编辑合同'
      this.form = {
        contractName: row.contractName,
        contractType: row.contractType,
        signedDate: row.signedDate,
        startDate: row.startDate,
        endDate: row.endDate,
        totalAmount: row.totalAmount,
        remark: row.remark
      }
      this.dialogVisible = true
    },

    // 保存合同
    async handleSave() {
      try {
        await this.$refs.formRef.validate()
        
        if (this.isEdit) {
          // 编辑
          const res = await contractApi.updateContract(this.editId, this.form)
          if (res.code === 200) {
            ElMessage.success('合同更新成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '更新失败')
          }
        } else {
          // 新增
          const res = await contractApi.addContract(this.form)
          if (res.code === 200) {
            ElMessage.success('合同创建成功')
            this.dialogVisible = false
            this.loadTableData()
          } else {
            ElMessage.error(res.message || '创建失败')
          }
        }
      } catch (error) {
        console.error('保存失败:', error)
      }
    },

    // 删除合同
    async handleDelete(row) {
      try {
        await ElMessageBox.confirm('确定要删除该合同吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await contractApi.deleteContract(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    },

    // 提交审批
    async handleSubmit(row) {
      try {
        await ElMessageBox.confirm('确定要提交该合同进行审批吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await contractApi.submitForApproval(row.id)
        if (res.code === 200) {
          ElMessage.success('提交审批成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '提交审批失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交审批失败:', error)
          ElMessage.error('提交审批失败')
        }
      }
    },

    // 批量提交审批
    async handleBatchSubmit() {
      if (this.selectedRows.length === 0) {
        ElMessage.warning('请选择要提交的合同')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要提交选中的 ${this.selectedRows.length} 个合同进行审批吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        let successCount = 0
        let failCount = 0
        
        for (const row of this.selectedRows) {
          try {
            const res = await contractApi.submitForApproval(row.id)
            if (res.code === 200) {
              successCount++
            } else {
              failCount++
            }
          } catch (error) {
            failCount++
          }
        }
        
        ElMessage.success(`批量提交完成：成功 ${successCount} 个，失败 ${failCount} 个`)
        this.loadTableData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量提交失败:', error)
          ElMessage.error('批量提交失败')
        }
      }
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        0: 'info',    // 草稿
        1: 'warning', // 待审批
        2: 'success', // 生效
        3: 'success', // 完成
        4: 'danger'   // 终止
      }
      return statusMap[status] || 'info'
    },

    // 查看合同详情
    async handleViewDetail(row) {
      this.detailDialogVisible = true
      this.contractDetail = null // 清空详情
      try {
        const res = await contractApi.getContractById(row.id)
        if (res.code === 200) {
          this.contractDetail = res.data
        } else {
          ElMessage.error(res.message || '加载合同详情失败')
        }
      } catch (error) {
        console.error('加载合同详情失败:', error)
        ElMessage.error('加载合同详情失败')
      }
    }
  }
}
</script>

<style scoped>
.contract-draft {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.template-selection {
  padding: 20px;
}

.template-filter .el-form-item {
  margin-bottom: 15px;
}

.contract-detail {
  padding: 20px;
}

.contract-items h3 {
  margin-top: 0;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}
</style>
